import 'package:flutter/foundation.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';

import '../../../data/models/bt_block.dart';
import '../../../data/models/bt_broadcaster.dart';
import '../../../part/bt_rc_im_engine.dart';
import '../../message/utils/bt_constants.dart';
import '../../profile/repository/bt_profile_repository.dart';
import '../../utils/bt_event_bus.dart';
import '../repository/bt_home_repository.dart';
import 'bt_local_broadcaster.dart';

class BtHomeModel extends ChangeNotifier {
  late final BtHomeRepository repository;
  late final BtProfileRepository profileRepository;

  final int _pageSize = 20;

  final PagingController<int, BtLocalBroadcaster> _pagingController = PagingController(firstPageKey: 0);

  PagingController<int, BtLocalBroadcaster> get pagingController => _pagingController;

  late PageRequestListener<int> _listener;

  List<BtBroadcaster> _broadcasters = [];

  List<BtBroadcaster> get broadcasters => _broadcasters;

  BtHomeModel() {
    repository = BtHomeRepository();
    profileRepository = BtProfileRepository();
    fetchRongCloudToken();
    fetchStrategy();

    _listener = (pageKey) {
      pageKey++;
      fetchBroadcasterList(pageKey);
    };
    _pagingController.addPageRequestListener(_listener);

    eventBus.on<BtEventFn>().listen((event) {
      if (event.refresh == block) {
        _pagingController.refresh();
      }
    });
  }

  Future<void> fetchStrategy() async {
    repository.getStrategy();
  }

  Future<void> fetchRongCloudToken() async {
    repository.getRongCloudToken((token) {
      BtRcImEngine().initRcImEngine(token);
    });
  }

  bool _isInBlockList(String userId, List<BtBlock> blockList) {
    int index = blockList.indexWhere((element) => element.broadcasterId == userId);

    return index != -1;
  }

  void fetchBroadcasterList(int pageKey) {
    profileRepository.getBlockList(pageKey, _pageSize, (blockList) {
      repository.fetchBroadcasterList(pageKey, _pageSize, (btBroadcasterList) {
        try {
          btBroadcasterList.removeWhere((element) => _isInBlockList(element.userId, blockList));
          final list = <BtLocalBroadcaster>[];
          _broadcasters = btBroadcasterList;
          for (int i = 0; i < _broadcasters.length; i++) {
            String title = '';
            String localAvatar = '';
            switch (i) {
              case 0:
                title = 'Americano';
                localAvatar = 'assets/images/bt_icon_americano_avatar.png';
                break;
              case 1:
                title = 'Cappuccino';
                localAvatar = 'assets/images/bt_icon_cappuccino_avatar.png';
                break;
              case 2:
                title = 'Latte';
                localAvatar = 'assets/images/bt_icon_latte_avatar.png';
                break;
              case 3:
                title = 'Caramel Macchiato';
                localAvatar = 'assets/images/bt_icon_cm_to_avatar.png';
                break;
              case 4:
                title = 'Espresso';
                localAvatar = 'assets/images/bt_icon_espresso_avatar.png';
                break;
            }
            if (i < 5) {
              list.add(BtLocalBroadcaster(
                  userId: _broadcasters[i].userId,
                  nickname: _broadcasters[i].nickname,
                  avatar: _broadcasters[i].avatar,
                  localAvatar: localAvatar,
                  title: title,
                  about: 'sales volume'));
            }
          }
          final isLastPage = list.length < _pageSize;
          if (isLastPage) {
            _pagingController.appendLastPage(list);
          } else {
            _pagingController.appendPage(list, pageKey);
          }
        } catch (error) {
          _pagingController.error = error;
        }
      });
    });
  }
}
